<template>
  <view class="pie-chart-container">
    <view class="chart-title" v-if="title">{{ title }}</view>
    <view class="pie-chart-wrapper">
      <!-- 饼图显示 - 使用简化的环形图 -->
      <view
        class="pie-chart"
        :style="{ width: size + 'px', height: size + 'px' }"
      >
        <!-- 背景圆 -->
        <view class="pie-background" :style="getPieBackgroundStyle()"></view>

        <view class="pie-center" v-if="showCenter">
          <view class="center-value">{{ centerValue }}</view>
          <view class="center-label">{{ centerLabel }}</view>
        </view>
      </view>
      <!-- 图例 -->
      <view class="pie-legend" v-if="showLegend">
        <view
          v-for="(item, index) in data"
          :key="index"
          class="legend-item"
          :class="{ 'legend-item-hidden': hiddenItems.includes(index) }"
          @click="toggleLegendItem(index)"
        >
          <view
            class="legend-color"
            :style="{ backgroundColor: colors[index % colors.length] }"
          ></view>
          <view class="legend-text">
            <text class="legend-label">{{ item.label }}</text>
            <text class="legend-value">{{ item.value }}</text>
            <text class="legend-percent">{{ getPercentage(item.value) }}%</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";

interface PieChartData {
  label: string;
  value: number;
}

interface Props {
  data: PieChartData[];
  title?: string;
  size?: number;
  colors?: string[];
  showLegend?: boolean;
  showCenter?: boolean;
  centerLabel?: string;
}

const props = withDefaults(defineProps<Props>(), {
  size: 200,
  colors: () => [
    "#667eea",
    "#764ba2",
    "#f093fb",
    "#f5576c",
    "#4facfe",
    "#00f2fe",
    "#43e97b",
    "#38f9d7",
    "#ffecd2",
    "#fcb69f",
    "#a8edea",
    "#fed6e3",
  ],
  showLegend: true,
  showCenter: true,
  centerLabel: "总计",
});

const hiddenItems = ref<number[]>([]);

// 计算总值
const totalValue = computed(() => {
  return props.data
    .filter((_, index) => !hiddenItems.value.includes(index))
    .reduce((sum, item) => sum + item.value, 0);
});

// 计算中心显示的值
const centerValue = computed(() => {
  return totalValue.value.toString();
});

// 获取百分比
const getPercentage = (value: number) => {
  if (totalValue.value === 0) return "0";
  const percentage = ((value / totalValue.value) * 100).toFixed(1);
  return percentage === "0.0" ? "0" : percentage;
};

// 生成饼图背景样式
const getPieBackgroundStyle = () => {
  if (props.data.length === 0 || totalValue.value === 0) {
    return {
      background: "#f0f0f0",
    };
  }

  // 计算每个数据项的百分比
  let currentPercentage = 0;
  const gradientStops: string[] = [];

  props.data.forEach((item, index) => {
    if (hiddenItems.value.includes(index)) return;

    const percentage = (item.value / totalValue.value) * 100;
    const color = props.colors[index % props.colors.length];

    // 即使值为0也要显示，但给一个很小的视觉空间
    const displayPercentage = percentage > 0 ? percentage : 0.5;

    gradientStops.push(`${color} ${currentPercentage}%`);
    currentPercentage += displayPercentage;
    gradientStops.push(`${color} ${currentPercentage}%`);
  });

  return {
    background: `conic-gradient(${gradientStops.join(", ")})`,
  };
};

// 切换图例项
const toggleLegendItem = (index: number) => {
  const hiddenIndex = hiddenItems.value.indexOf(index);
  if (hiddenIndex > -1) {
    hiddenItems.value.splice(hiddenIndex, 1);
  } else {
    hiddenItems.value.push(index);
  }
};
</script>

<style lang="scss" scoped>
.pie-chart-container {
  width: 100%;

  .chart-title {
    text-align: center;
    font-size: 14px;
    font-weight: 600;
    color: #1a1a1a;
    margin-bottom: 8px;
  }

  .pie-chart-wrapper {
    display: flex;
    align-items: center;
    gap: 16px;

    .pie-chart {
      position: relative;
      border-radius: 50%;
      flex-shrink: 0;

      .pie-background {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }

      .pie-center {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #ffffff;
        border-radius: 50%;
        width: 60%;
        height: 60%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        z-index: 10;

        .center-value {
          font-size: 16px;
          font-weight: 700;
          color: #1a1a1a;
          line-height: 1;
        }

        .center-label {
          font-size: 10px;
          color: #666;
          margin-top: 2px;
        }
      }
    }

    .pie-legend {
      flex: 1;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: opacity 0.3s ease;

        &.legend-item-hidden {
          opacity: 0.4;
        }

        .legend-color {
          width: 10px;
          height: 10px;
          border-radius: 2px;
          flex-shrink: 0;
        }

        .legend-text {
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .legend-label {
            font-size: 12px;
            color: #1a1a1a;
            font-weight: 500;
          }

          .legend-value {
            font-size: 12px;
            color: #666;
            margin-left: 6px;
          }

          .legend-percent {
            font-size: 10px;
            color: #999;
            margin-left: 3px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 600px) {
  .pie-chart-wrapper {
    flex-direction: column;
    gap: 12px;

    .pie-legend {
      width: 100%;

      .legend-item {
        margin-bottom: 6px;
        gap: 4px;

        .legend-text {
          .legend-label {
            font-size: 11px;
          }

          .legend-value {
            font-size: 11px;
            margin-left: 4px;
          }

          .legend-percent {
            font-size: 9px;
            margin-left: 2px;
          }
        }
      }
    }
  }
}
</style>
